package com.zprmb.udzt.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zprmb.udzt.BaseActivity;
import com.zprmb.udzt.R;
import com.zprmb.udzt.V6LoginActivity;
import com.zprmb.udzt.V6WebviewChild;
import com.zprmb.udzt.WebViewActivity;
import com.zprmb.udzt.bean.ZhiTouBean;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ExplosionField;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.NumUtil;
import com.zprmb.udzt.util.TimeUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.zhitoudialog.ZhiTouAlertDialog;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class V6ZhiTouDexterityPayInActivity extends BaseActivity implements View.OnClickListener , ZhiTouAlertDialog.OnSureClickListener {
    //    private AddAndSubView addAndSubView;
    private TextView tv_v6_dexterity_pay_in_keyong;
    //    private TextView tv_v6_dexterity_pay_in_chiyou;
    private TextView tv_v6_dexterity_pay_in_shouyi;
    private Button tv_v6_dexterity_pay_in_updata;
    private Double million;
    private Double inAmount;
    private TextView tv_product_shouyi;
    private int remainAmount;
    private int increaseNum;// 增量
    private int minAmount;
    private String productId;
    private Double maxAmount;


    private Double availableAmount;
    private ListView lv_comment;

    private TextView check_mAgreement;
    private CheckBox check;
    private LinearLayout li_dexterity;
    private ExplosionField mExplosionField;//粉碎动画执行方法类
    private TextView tv_v6_dexterity_pay_in_daotime;
    private TextView tv_v6_dexterity_pay_in_shengyu;
    DecimalFormat df = new DecimalFormat("###0.00");
    private List<String> list = new ArrayList<String>();
    //
    private TextView tv_mAgreement;

    String receivemoney = "";

    //输入框的money

    private EditText edit_zhitoumoney;
//剩余可投金额

    String shengyu;

    //剩余可投金额的布局

    LinearLayout layout_investall;

    TextView text_yue;

    TextView text_quantou;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_v6zhitou);
        setImmersionStatus();
        setContentInview(this).setVisibility(View.INVISIBLE);
        setTitle("转入", V6ZhiTouDexterityPayInActivity.this);
        setgoback(V6ZhiTouDexterityPayInActivity.this);
        check = (CheckBox) findViewById(R.id.check);
        tv_mAgreement = (TextView) findViewById(R.id.tv_mAgreement);
        check_mAgreement = (TextView) findViewById(R.id.check_mAgreement);
        li_dexterity = (LinearLayout) findViewById(R.id.li_dexterity);

        tv_v6_dexterity_pay_in_shengyu = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_shengyu);
//        addAndSubView = (AddAndSubView) findViewById(R.id.add_subview);
        tv_v6_dexterity_pay_in_keyong = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_keyong);
//        tv_v6_dexterity_pay_in_chiyou = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_chiyou);
        tv_v6_dexterity_pay_in_shengyu = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_shengyu);
        tv_v6_dexterity_pay_in_updata = (Button) findViewById(R.id.tv_v6_dexterity_pay_in_updata);
        tv_v6_dexterity_pay_in_daotime = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_daotime);
        tv_product_shouyi = (TextView) findViewById(R.id.tv_product_shouyi);

        receivemoney = String.valueOf(getIntent().getIntExtra("investamount", 0));
        edit_zhitoumoney = (EditText) findViewById(R.id.edit_zhitoumoney);
        edit_zhitoumoney.setText(receivemoney);
        tv_product_shouyi.setVisibility(View.INVISIBLE);
//投资按钮
        tv_v6_dexterity_pay_in_updata.setOnClickListener(this);

        layout_investall = (LinearLayout) findViewById(R.id.layout_investall);
        text_yue = (TextView) findViewById(R.id.text_yue);
        text_quantou = (TextView) findViewById(R.id.text_quantou);
        layout_investall.setOnClickListener(this);
        text_yue.setOnClickListener(this);
        text_quantou.setOnClickListener(this);
        check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    tv_v6_dexterity_pay_in_updata.setEnabled(true);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.v6button);
                } else {
                    tv_v6_dexterity_pay_in_updata.setEnabled(false);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.btn_unclick);
                }
            }
        });
        check_mAgreement.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (check.isChecked()) {
                    tv_v6_dexterity_pay_in_updata.setEnabled(false);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.btn_unclick);
                    check.setChecked(false);
                } else {
                    tv_v6_dexterity_pay_in_updata.setEnabled(true);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.v6button);
                    check.setChecked(true);
                }
            }
        });
        tv_mAgreement.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent2 = new Intent(V6ZhiTouDexterityPayInActivity.this,
                        WebViewActivity.class);
                intent2.putExtra("url", "landing/currentAgreement?app=true&token=");


                intent2.putExtra("share", 1);
                intent2.putExtra("titleview", 1);
                intent2.putExtra("title", "《智投宝授权委托书》");
                startActivity(intent2);
            }
        });

//        verityUser();

    }


    private void payIn() {
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                LogUtils.e("转入", jsonObject.toString());

                if (jsonObject.optInt("success") == 1) {
                    setContentInview(V6ZhiTouDexterityPayInActivity.this).setVisibility(View.VISIBLE);

                    JSONObject json = jsonObject.optJSONObject("data");
                    tv_v6_dexterity_pay_in_keyong.setText(df.format(Double
                            .parseDouble(json.optString("userFundAvailableAmount")))
                    );
                  /*  tv_v6_dexterity_pay_in_chiyou.setText(df.format(Double
                            .parseDouble(json.optString("currentAmount")))
                    );*/

                    remainAmount = json.optInt("maxAmount");
                    increaseNum = json.optInt("increaseNum");
                    minAmount = json.optInt("minAmount");
                    maxAmount = json.optDouble("holdCapAmount");
                    tv_v6_dexterity_pay_in_shengyu.setText(NumUtil.getQiantwo(json.optString("maxAmount")) + "元");
                    shengyu = json.optString("maxAmount");

                    String time = TimeUtils.formatTime(new Date(Long
                            .valueOf(json.optString("nextWorkDay"))));
                    Log.e("时间", time);

                    tv_v6_dexterity_pay_in_daotime.setText("预期收益到账时间 :" + time);
                    productId = json.optString("productId");
                    inAmount = json.optDouble("maxTransferAmount");
                    availableAmount = json.optDouble("availableAmount");

//					addAndSubView.setMinnum(minAmount);
                    Gson gson = new Gson();
                    list = gson.fromJson(json.optString("promptList"),
                            new TypeToken<ArrayList<String>>() {
                            }.getType());
//
                    String s = "";
                    for (int i = 0; i < list.size(); i++) {
                        s = s + list.get(i);
                    }

                   /* addAndSubView.setincreaseNum(increaseNum);
                    if (getIntent().getIntExtra("investamount", 0) != 0) {
                        addAndSubView.setNum(getIntent().getIntExtra("investamount", 0));
                    }*/
                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                V6LoginActivity.class);
                        intent.putExtra("close", 1);
                        intent.putExtra("web", 1);
                        startActivity(intent);
                    } else {
                        ToastUtil.showCenterToast(V6ZhiTouDexterityPayInActivity.this,
                                jsonObject.optString("comment"));
                    }

                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                setContentInview(V6ZhiTouDexterityPayInActivity.this).setVisibility(View.INVISIBLE);

                Toast.makeText(V6ZhiTouDexterityPayInActivity.this, "请求失败   请检查网络设置",
                        2000).show();
            }
        };
        vollery.setShow(true);
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("client", "android");
        vollery.setRequestMethod(1);
        vollery.execute(this, Constant.URL + "/api/v2/claim/fund/intelli/in", "");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        payIn();
    }

   /* private void changeComment() {
        if (addAndSubView.getNum() > availableAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"请输入转入金额");

//            tv_tishi.setText("账户可用余额不足");
            return;
        }
        if (addAndSubView.getNum() <= 0) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"请输入转入金额");

//            tv_tishi.setText("请输入转入金额");
            return;
        }
        if (addAndSubView.getNum() < minAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额" + minAmount + "元起");

//            tv_tishi.setText("转入金额" + minAmount + "元起");
            return;
        }

        if (addAndSubView.getNum() > inAmount
                && addAndSubView.getNum() <= remainAmount) {


//            tv_tishi.setText("转入金额超出持有上限");
            return;
        }
        if (addAndSubView.getNum() > maxAmount
                ) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额超出持有上限");

//            tv_tishi.setText("输入金额超出持有上限" + Regular.getDecimalFormatZero(maxAmount / 10000) + "万元");
            return;
        }
        if (addAndSubView.getNum() > remainAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"项目剩余金额不足");

//            tv_tishi.setText("项目剩余金额不足");
            return;
        }
        if ((addAndSubView.getNum()
                - minAmount) % increaseNum != 0) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额的增量要为" + increaseNum + "的倍数");

//            tv_tishi.setText("转入金额的增量要为" + increaseNum + "的倍数");
            return;
        }
        if ((addAndSubView.getNum()
                - minAmount) % increaseNum != 0 || addAndSubView.getNum() > remainAmount || addAndSubView.getNum() > inAmount
                && addAndSubView.getNum() < remainAmount || addAndSubView.getNum() < minAmount || addAndSubView.getNum() <= 0) {

        } else {

        }
    }*/

    private void verityUser() {
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {
                    Log.d(jsonObject.toString(), "44444444444444");
                    Gson gson = new Gson();
                    ZhiTouBean zhiTouBean=new ZhiTouBean();
                    zhiTouBean=gson.fromJson(jsonObject.toString(),ZhiTouBean.class);
                    JSONObject json = jsonObject.optJSONObject("data");
                    Intent intent = null;

                    if (!json.optBoolean("isBindCard")) {
                        intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                V6WebviewChild.class);
                        intent.putExtra("url", Constant.URL + "h5/account/bankcard/bind/view?app=true&token=");
                        intent.putExtra("title", "智投宝");
                        startActivity(intent);
                        return;
                    }

                   /* intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                            PayZhitouActivity.class);*/


                    if (Double.valueOf(tv_v6_dexterity_pay_in_keyong.getText().toString()).intValue() > Double.valueOf(edit_zhitoumoney.getText().toString()).intValue()) {
                      /*  intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                PayDexterityActivity.class);*/
                        intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                PayZhitouActivity.class);

                        intent.putExtra("type", "IN");


                        tv_v6_dexterity_pay_in_updata
                                .setBackgroundResource(R.drawable.btn_unclick);
                        tv_v6_dexterity_pay_in_updata.setEnabled(false);
                        tv_v6_dexterity_pay_in_updata
                                .setBackgroundResource(R.drawable.v6button);
                        tv_v6_dexterity_pay_in_updata.setEnabled(true);
//                    intent.putExtra("amount", addAndSubView.getNum() + "");
                        intent.putExtra("amount", edit_zhitoumoney.getText().toString());

                        intent.putExtra("productId", productId);
                        LogUtils.e("智投宝id", productId);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_from_bottom,
                                R.anim.slide_out_to_bottom);
                    } else {
                        intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                PayZhitouActivity.class);

                        intent.putExtra("amount", "100");
                        intent.putExtra("path", "100");
                        intent.putExtra("card_no", zhiTouBean.getData().getCardNo());
                        intent.putExtra("bank_name", zhiTouBean.getData().getBankNameEn());
                        intent.putExtra("loan_id", productId);
                        intent.putExtra("type", "IN");
                        intent.putExtra("investment_Amount", "400");
                        intent.putExtra("coupon_id", "");
                        intent.putExtra("coupon_type", "");
                      /*  hpay/v3/h5recharge
                        String amount 充值金额
                        String path 充值类型
                        String card_no 银行卡号
                        bank_name 银行编号
                        String token
                        String loan_id 产品ID
                        String type 产品类型
                        String investment_Amount 投资金额
                        String coupon_id 道具id
                        String coupon_type 道具类型*/


                        tv_v6_dexterity_pay_in_updata
                                .setBackgroundResource(R.drawable.btn_unclick);
                        tv_v6_dexterity_pay_in_updata.setEnabled(false);
                        tv_v6_dexterity_pay_in_updata
                                .setBackgroundResource(R.drawable.v6button);
                        tv_v6_dexterity_pay_in_updata.setEnabled(true);
//                    intent.putExtra("amount", addAndSubView.getNum() + "");
                        intent.putExtra("amount", edit_zhitoumoney.getText().toString());

                        intent.putExtra("productId", productId);
                        LogUtils.e("智投宝id", productId);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_from_bottom,
                                R.anim.slide_out_to_bottom);
                    }

                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6ZhiTouDexterityPayInActivity.this,
                                V6LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtil.showCenterToast(V6ZhiTouDexterityPayInActivity.this,
                                jsonObject.optString("comment"));
                    }
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("client", "android");
        vollery.setShow(true);
        vollery.setRequestMethod(0);
        vollery.execute(V6ZhiTouDexterityPayInActivity.this, Constant.URL
                + "/api/v5/user/userInfo", "");
    }

    /*  hpay/v3/h5recharge
      String amount 充值金额
      String path 充值类型
      String card_no 银行卡号
      bank_name 银行编号
      String token
      String loan_id 产品ID
      String type 产品类型
      String investment_Amount 投资金额
      String coupon_id 道具id
      paramMap.put("client", Source.WEB.name

  ());
      String coupon_type 道具类型*/
    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
    private PopupWindow popWindow;
    private void showPopupWindow(View parent) {
        if (popWindow == null) {
            View view = LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null);
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        ImageView iv_v4_pay_finish= (ImageView) view.findViewById(R.id.iv_v4_pay_finish);
        //点击popwindow消失

        View view_popdismiss=view.findViewById(R.id.pop_top);
        view_popdismiss.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        iv_v4_pay_finish.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        //转入按钮
        Button btn_dexterity_invest= (Button) view.findViewById(R.id.btn_dexterity_invest);
        btn_dexterity_invest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                verityUser();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_v6_dexterity_pay_in_updata:
               /* if (check.isChecked() == false) {
                    ToastUtil.showCenterToast(V6ZhiTouDexterityPayInActivity.this,
                            "请阅读并同意智投宝授权委托书");
                } else if (Double.valueOf(shengyu).intValue() <= 0) {
                    ToastUtil.showCenterToast(V6ZhiTouDexterityPayInActivity.this,
                            "当前剩余可投金额为0元不可转入");
                } else {

                }*/
//                verityUser();
                showPopupWindow(tv_v6_dexterity_pay_in_updata);

                break;
            case R.id.layout_investall:

                break;
            case R.id.text_yue:

                break;
            case R.id.text_quantou:

                break;


        }


    }

    @Override
    public void onConfirm() {

    }

    @Override
    public void onCancle() {

    }
}
